const mongoose = require("mongoose");

const TaskReminderSchema = new mongoose.Schema(
  {
    task: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Task",
      required: true,
    },
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    type: {
      type: String,
      enum: ["due_date", "custom", "milestone"],
      required: true,
    },
    title: {
      type: String,
      required: true,
      trim: true,
      maxlength: 200,
    },
    message: {
      type: String,
      trim: true,
      maxlength: 500,
      default: "",
    },
    remindAt: {
      type: Date,
      required: true,
    },
    isActive: {
      type: Boolean,
      default: true,
    },
    isSent: {
      type: Boolean,
      default: false,
    },
    sentAt: {
      type: Date,
      default: null,
    },
    // 提醒方式
    methods: {
      type: [String],
      enum: ["notification", "email"],
      default: ["notification"],
    },
    // 重复提醒设置
    repeat: {
      enabled: { type: Boolean, default: false },
      interval: {
        type: String,
        enum: ["hourly", "daily", "weekly"],
        default: "daily",
      },
      count: { type: Number, default: 1 }, // 重复次数
      currentCount: { type: Number, default: 0 }, // 当前重复次数
    },
    // 额外配置
    metadata: {
      type: mongoose.Schema.Types.Mixed,
      default: {},
    },
  },
  { timestamps: true }
);

// 索引优化
TaskReminderSchema.index({ task: 1, user: 1 });
TaskReminderSchema.index({ remindAt: 1, isActive: 1, isSent: 1 });
TaskReminderSchema.index({ user: 1, isActive: 1 });

// 虚拟字段：是否已过期
TaskReminderSchema.virtual("isExpired").get(function () {
  return new Date() > this.remindAt;
});

// 虚拟字段：是否即将到期（1小时内）
TaskReminderSchema.virtual("isUpcoming").get(function () {
  const oneHour = 60 * 60 * 1000;
  const now = new Date();
  return (
    this.remindAt > now && this.remindAt <= new Date(now.getTime() + oneHour)
  );
});

// 确保虚拟字段在JSON序列化时包含
TaskReminderSchema.set("toJSON", { virtuals: true });

const TaskReminder = mongoose.model("TaskReminder", TaskReminderSchema);

module.exports = TaskReminder;
